#!/usr/bin/env node

const http = require('http'),
      qs = require('querystring'),
      fs = require('fs'),
      log = console.log;

let items = loadItems(),
    result = {
      status : 200,
      reason : 'ok'
    };

process.on('SIGTNT', ()=>{
  saveItems();
});

function loadItems(){
  log('loadItems');
  try{
    let items = fs.readFileSync('./12-items.txt').toString('utf-8');
    items = JSON.parse(items);
    return items;
  }catch(e){
    return [];
  }
}

function saveItems(){
  log('saveItems');
  fs.writeFileSync('./12-items.txt',JSON.stringify(items));
}
    
http.createServer((req,res) => {
  logRequest(req);

  if(req.url.slice(0,5) !== '/todo') {
    let html = fs.readFileSync('./12-todo.html');
    if(req.url == '/'){
      res.end(html);
    }else if(req.url == '/12-todo.js'){
      fs.createReadStream('./12-todo.js').pipe(res);
    }else{
      res.end('not api request and not page request!');
    }
    return;
  }

  switch(req.method){
    case 'GET':
      select(req,res);
      
      break;
      //curl -X GET -d 'item=ss' http://localhost:8080/todo 得到全部

    case 'POST':
      insert(req,res);
      break; 
      //curl -X POST -d 'item=ss' http://localhost:8080/todo 添加一项

    case 'PUT':
      update(req,res);
      break;
      //curl -X PUT -d 'item=ss' http://localhost:8080/todo:0 修改下标为0的为ss
    case 'DELETE':
      remove(req,res);
      break;
      //curl -X DELETE http://localhost:8080/todo:0 删除下标为0的为ss
    default:
      res.end(`${res.method} not support`);
      break;
      
  }  

}).listen(8080);

function select(req,res){
  result.data = items;
  res.end(JSON.stringify(result));
}
function insert(req,res){
  let data = '';

  req.on('data', chunk => data+=chunk);
  req.on('end', () => {
    let item = qs.parse(data).item;

    if(item !== '' && typeof item !== undefined){
      items.push(item);
      res.end(JSON.stringify(result));
    }else{
      result.status = 401;
      result.reason = 'item is empty';
      res.end(result);
    }
  });
}

function update(req,res){
  // get id
  let id = req.url.split(':')[1];

  // validate id
  // data type
  // value min=0,max=items.length
  
  // get item
  let data = '';
  req.on('data', chunk => data += chunk);
  req.on('end', () => {
    // update items[id] = item
    let item = qs.parse(data).item;
    if(item !== '' && typeof item !== 'undefined'){
      items[id] = item;
      res.end(JSON.stringify(result));
    }else{
      result.status = 401;
      result.reason = 'item is empty';
      res.end(JSON.stringify(result));
    }
  });
  res.end(req.method);
}
function remove(req,res){
  // get id
  let id = req.url.split(':')[1];
  // id not exist  del all
  if(typeof id === 'undefined'){
    items = [];
    result.status = 200;
    result.reason = 'delete all success';
    res.end(JSON.stringify(result));
    return;
  }

  // id exist
  // validate id
  // id is ok del items[id]
  items = items.splice(id,1);
  result.status = 200;
  result.reason = 'delete all success';
  res.end(JSON.stringify(result));
}
function logRequest(req){
  log(`${req.method} ${req.url} ${req.httpVersion}`);
  log(req.headers);
  log();
}
